import { Directive, DirectiveBinding, nextTick } from 'vue';
const dragDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    nextTick(() => {
      drag(el, binding);
    });
  },
  // updated(el: HTMLElement, binding: DirectiveBinding) {
  //   nextTick(() => {
  //     drag(el, binding);
  //   });
  // },
  // 最后卸载时，清除事件绑定
  unmounted(el) {
    const header = el.children[0].children[0];
    header.onmousedown = null;
  },
};
const drag = (el: HTMLElement, binding: DirectiveBinding) => {
  /**
   * 这里是跟据 dialog 组件的 dom 结构来写的
   * target: dialog 组件的容器元素
   * header：dialog 组件的头部区域，也是就是拖拽的区域
   */
  const target = el as HTMLElement;
  const header = target.children[0] as HTMLElement;

  header.onmousedown = e => {
    // 记录按下时鼠标的坐标和目标元素的 left、top 值
    const currentX = e.clientX - target.offsetLeft;
    const currentY = e.clientY - target.offsetTop;
    const maxLeft = document.body.offsetWidth - target.offsetWidth;
    const maxTop = document.body.offsetHeight - target.offsetHeight;
    document.onmousemove = event => {
      // 鼠标移动时计算每次移动的距离，并改变拖拽元素的定位
      let left = event.clientX - currentX;
      let top = event.clientY - currentY;
      if (-left >= 0) {
        left = 0;
      } else if (left > maxLeft) {
        left = maxLeft;
      }

      if (-top > 0) {
        top = 0;
      } else if (top > maxTop) {
        top = maxTop;
      }

      target.style.left = `${left}px`;
      target.style.top = `${top}px`;

      // 阻止事件的默认行为，可以解决选中文本的时候拖不动
      return false;
    };

    // 鼠标松开时，拖拽结束
    document.onmouseup = () => {
      document.onmousemove = null;
      document.onmouseup = null;
    };
  };
};
export default dragDirective;
